package cool.mor.service.impl;

import cool.mor.dao.DepartmentRepository;
import cool.mor.dao.EmployeeRepository;
import cool.mor.dto.EmployeeDto;
import cool.mor.entity.Employee;
import cool.mor.form.EmployeeForm;
import cool.mor.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Ivan
 *
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    EmployeeRepository employeeRepository;
    @Autowired
    DepartmentRepository departmentRepository;

    /**
     *  *         Employee employee = employeeRepository.findById(id).get();
     *              不适用jpa的代理对象，有值则返回对应的值，无值则返回null
     * @param id
     * @return
     */
    @Override
    public EmployeeDto queryById(String id) {
        EmployeeDto employeeDto = new EmployeeDto();
        Employee employee = employeeRepository.findById(id).get();
        BeanUtils.copyProperties(employee,employeeDto);
        /**
         * 将雇员表中的dept no转化为 部门名称
         */
        employeeDto.setDepartmentName(departmentRepository.findById(employee.getDeptNo()).get().getDepartmentName());
        employeeDto.setCode("200");
        employeeDto.setMessage("查找成功");
        return employeeDto;
    }

    @Override
    public EmployeeDto update(EmployeeForm employeeForm) {
        EmployeeDto employeeDto = new EmployeeDto();
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeForm,employee);
        employeeRepository.save(employee);
        employeeDto.setCode("200");
        employeeDto.setMessage("修改成功");
        return employeeDto;
    }
}
